import Koa from "koa";
import KoaBody from "koa-body";
import KoaJwt from "koa-jwt";

import User from "./routes/user";
import config from "./config";
import http from "http";
import { Server } from "socket.io";
// import webSocket from "./chatCore/webSocket";
import socketIo from "./chatCore/socketIo";

const app = new Koa();
// const server = http.createServer(app.callback());
const io = new Server(config.port + 1, {
  // TODO 本地不能做跨域限制，electron 在本地使用ajax 容易跨域，后续如果找到方案，可更改此处
  cors: {
    // origin: "http://localhost:5173",
  },
});

app.use(KoaBody());
// 注意：放在路由前面
app.use(
  KoaJwt({ secret: config.JwtSecret }).unless({
    // 配置白名单
    path: config.JwtWhileList,
  })
);
/* 验证token */
app.use((ctx, next) => {
  return next().catch((err) => {
    if (err.status === 401) {
      ctx.status = 401;
      ctx.body = "Protected resource, use Authorization header to get access\n";
    } else {
      throw err;
    }
  });
});

// 路由
app.use(User.routes()).use(User.allowedMethods());

app.use(async (ctx) => {
  console.log(ctx);
  // console.log("404 Not Found")
});

// webSocket 事件处理
// webSocket.startWebSocketServer();

// Socket.IO 事件处理
socketIo.startSocketIoServer(io);

app.listen(config.port, () => {
  console.log("服务器正在 http://localhost:3000 上运行");
});
